package com.skytech.tax.customsdatawarehouse.electronicport.customsdeclarations.domain.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.skytech.tax.customsdatawarehouse.common.util.SecurityUtil;
import com.skytech.tax.customsdatawarehouse.electronicport.customsdeclarations.domain.dao.CustomsDeclarationDao;
import com.skytech.tax.customsdatawarehouse.electronicport.customsdeclarations.domain.dao.CustomsDeclarationFileDao;
import com.skytech.tax.customsdatawarehouse.electronicport.customsdeclarations.domain.dao.CustomsDeclarationSimpleDao;
import com.skytech.tax.customsdatawarehouse.electronicport.customsdeclarations.domain.entity.CustomsDeclaration;
import com.skytech.tax.customsdatawarehouse.electronicport.customsdeclarations.domain.entity.CustomsDeclarationFile;
import com.skytech.tax.customsdatawarehouse.electronicport.customsdeclarations.domain.entity.CustomsDeclarationSimple;
import com.skytech.tax.customsdatawarehouse.electronicport.customsdeclarations.domain.entity.ElectronicPortCustomsDeclaration;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Lianhong
 * @since 2021/6/9
 */
@Service("electronicPort.customsDeclarationService")
public class CustomsDeclarationService {

    private static final Logger LOGGER = LoggerFactory.getLogger(CustomsDeclarationService.class);

    @Value("${customsdatawarehouse.token}")
    private String token;

    @Resource(name = "electronicPort.customsDeclarationDao")
    private CustomsDeclarationDao customsDeclarationDao;

    @Resource(name = "electronicPort.customsDeclarationSimpleDao")
    private CustomsDeclarationSimpleDao customsDeclarationSimpleDao;

    @Resource
    private CustomsDeclarationFileDao customsDeclarationFileDao;

    public String getCustomsDeclarations() {
        List<CustomsDeclaration> list = customsDeclarationDao.findAll();
        if (CollectionUtils.isEmpty(list)) return StringUtils.EMPTY;
        JSONArray customsDeclarations = new JSONArray();
        list.forEach(item -> customsDeclarations.add(JSON.parseObject(item.getCustomsDeclaration())));
        return SecurityUtil.encrypt3DES(token, JSON.toJSONString(customsDeclarations));
    }

    public String getCustomsDeclarations(List<String> entryIds) {
        if (CollectionUtils.isEmpty(entryIds)) return StringUtils.EMPTY;
        List<List<String>> parts = Lists.partition(entryIds, 500);
        JSONArray customsDeclarations = new JSONArray();
        parts.forEach(entryIdList -> {
            List<CustomsDeclaration> list = customsDeclarationDao.findByEntryIds(entryIdList);
            list.forEach(item -> customsDeclarations.add(JSON.parseObject(item.getCustomsDeclaration())));
        });
        return SecurityUtil.encrypt3DES(token, JSON.toJSONString(customsDeclarations));
    }

    @Transactional
    public String saveCustomsDeclaration(String declaration) {
        if (StringUtils.isEmpty(declaration)) return StringUtils.EMPTY;
        String customsDeclarationText = SecurityUtil.decrypt3DES(token, declaration);
        try {
            ElectronicPortCustomsDeclaration electronicPortCustomsDeclaration = JSON.parseObject(customsDeclarationText, ElectronicPortCustomsDeclaration.class);
            if (electronicPortCustomsDeclaration == null) return StringUtils.EMPTY;

            CustomsDeclaration customsDeclaration = electronicPortCustomsDeclaration.buildCustomsDeclaration();
            if (customsDeclaration == null) return StringUtils.EMPTY;

            CustomsDeclarationSimple customsDeclarationSimple = electronicPortCustomsDeclaration.buildCustomsDeclarationSimple(customsDeclaration.getiEDate());
            if (customsDeclarationSimple == null) return StringUtils.EMPTY;

            if (!customsDeclaration.isSameYear()) return StringUtils.EMPTY;

            this.deleteByEntryId(customsDeclaration.getEntryId());

            customsDeclarationDao.save(customsDeclaration);
            customsDeclarationSimpleDao.save(customsDeclarationSimple);
            return SecurityUtil.encrypt3DES(token, customsDeclaration.getCustomsDeclaration());
        } catch (Exception e) {
            LOGGER.error("保存进出口报关单错误", e);
            return StringUtils.EMPTY;
        }
    }

    public String getCustomsDeclaration(String entryId) {
        CustomsDeclaration customsDeclaration = customsDeclarationDao.findByEntryId(entryId);
        if (customsDeclaration == null) return StringUtils.EMPTY;
        return SecurityUtil.encrypt3DES(token, customsDeclaration.getCustomsDeclaration());
    }

    public void deleteByEntryId(String entryId) {
        customsDeclarationDao.delete(entryId);
        customsDeclarationSimpleDao.delete(entryId);
    }

    /**
     * 更新出口报关单
     *
     * @param entryId 出口报关单号
     * @param request 更新的数据 {"flagDec": "3", "opMode": "MOD",}
     */
    public void updateCustomsDeclaration(String entryId, String request) {
        if (StringUtils.isEmpty(request)) return;
        String text = SecurityUtil.decrypt3DES(token, request);
        JSONObject json = JSON.parseObject(text);
        String decType = json.getString("decType");
        String flagDec = json.getString("flagDec");
        String opMode = json.getString("opMode");
        customsDeclarationDao.update(entryId, decType, flagDec, opMode);
    }

    public boolean existsCustomsDeclaration(String entryId, String iEDate) {
        return customsDeclarationSimpleDao.exists(entryId, iEDate);
    }

    public String existsCustomsDeclarations(List<CustomsDeclarationSimple> simpleList) {
        if (CollectionUtils.isEmpty(simpleList)) return StringUtils.EMPTY;
        List<List<CustomsDeclarationSimple>> parts = Lists.partition(simpleList, 500);
        List<String> result = new ArrayList<>();
        parts.forEach(item -> result.addAll(customsDeclarationSimpleDao.exists(item)));
        return StringUtils.join(result, ",");
    }

    public String customsDeclarationFile(String entryId) {
        CustomsDeclarationFile customsDeclarationFile = customsDeclarationFileDao.findByEntryId(entryId);
        return SecurityUtil.encrypt3DES(token, JSON.toJSONString(customsDeclarationFile));
    }

    public void saveCustomsDeclarationFile(String entryId, String storedFile) {
        CustomsDeclarationFile customsDeclarationFile = new CustomsDeclarationFile(entryId, storedFile);
        customsDeclarationFileDao.save(customsDeclarationFile);

    }

    public boolean customsDeclarationFileStored(String entryId) {
        return customsDeclarationFileDao.exists(entryId);
    }


    public void deleteCustomsDeclarationFile(String entryId) {
        customsDeclarationFileDao.delete(entryId);
    }

}
